import mysql from 'mysql2/promise';
import configManager from '#src/config/config.js';
import {logger} from '#src/common/utils/logger.js';

// 删除sql-parser导入
// import Parser from 'sql-parser';

/**
 * SQL数据库操作类，提供安全的数据库连接和查询执行
 */
export class SQL {
     static pool;
    static initialized = false;
    static initializationPromise = null;

    // 删除SQL注入风险模式和关键字验证相关代码
    // static RISK_PATTERNS = [...];
    // static ALLOWED_KEYWORDS = new Set([...]);
    // static IDENTIFIER_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;

    /**
     * 初始化数据库连接池
     * @returns {Promise<mysql.Pool>} 数据库连接池
     */
    static async initPool() {
        if (this.initialized) return this.pool;
        if (this.initializationPromise) return this.initializationPromise;

        try {
            this.initializationPromise = this._createPool();
            this.pool = await this.initializationPromise;
            this.initialized = true;
            logger.info('数据库连接池初始化成功');
            return this.pool;
        } catch (error) {
            logger.error('数据库连接池初始化失败', {
                error: error.message,
                config: { host: DbConfig.host, database: DbConfig.database }
            });
            throw error;
        }
    }


  /**
     * 创建数据库连接池
     * @returns {Promise<mysql.Pool>} 数据库连接池
     */
    static async _createPool() {
         // 添加DbConfig变量声明
        const DbConfig = configManager.dbConfig;
    if (!DbConfig.host || !DbConfig.user) {
        throw new Error('数据库配置不完整: 缺少主机或用户名');
    }

        const poolConfig = {
            host: DbConfig.host,
            user: DbConfig.user,
            password: DbConfig.password,
            database: DbConfig.database,
            port: DbConfig.port || 3306,
            waitForConnections: DbConfig.waitForConnections ?? true,
            connectionLimit: DbConfig.connectionLimit ?? 10,
            queueLimit: DbConfig.queueLimit ?? 0,
            enableKeepAlive: DbConfig.enableKeepAlive ?? true,
            keepAliveInitialDelay: DbConfig.keepAliveInitialDelay ?? 30000
        };

        const pool = mysql.createPool(poolConfig);
        const connection = await pool.getConnection();
        connection.release();
        return pool;
    }


     /**
     * 执行SQL查询
     * @param {string} sql - SQL查询语句
     * @param {Array|Object} params - 查询参数
     * @param {Object} context - 查询上下文，用于日志记录
     * @returns {Promise<Object>} 查询结果
     */
    static async query(sql, params, context = {}) {
        if (!this.initialized) {
            await this.initPool();
        }

        const startTime = Date.now();
        try {
            // 删除SQL验证调用
            // this._validateInput(sql, params);
            const [results] = await this.pool.execute(sql, params);

            logger.info('SQL查询完成', {
                ...context,
                executionTime: Date.now() - startTime,
                rowCount: Array.isArray(results) ? results.length : 0
            });

            return results;
        } catch (error) {
            logger.error('SQL查询失败', {
                ...context,
                error: error.message,
                executionTime: Date.now() - startTime
            });
            throw new Error(`数据库查询错误: ${error.message}`);
        }
    }

    /**
     * 使用现有连接执行SQL查询
     * @param {mysql.PoolConnection} connection - 数据库连接
     * @param {string} sql - SQL查询语句
     * @param {Array|Object} params - 查询参数
     * @param {Object} context - 查询上下文，用于日志记录
     * @returns {Promise<Object>} 查询结果
     */
    static async queryWithConnection(connection, sql, params, context = {}) {
        const startTime = Date.now();
        try {
            // 删除SQL验证调用
            // this._validateInput(sql, params);
            const [results] = await connection.execute(sql, params);

            logger.info('SQL查询完成(事务)', {
                ...context,
                executionTime: Date.now() - startTime,
                rowCount: Array.isArray(results) ? results.length : 0
            });

            return results;
        } catch (error) {
            logger.error('SQL查询失败(事务)', {
                ...context,
                error: error.message,
                executionTime: Date.now() - startTime
            });
            throw new Error(`事务查询错误: ${error.message}`);
        }
    }

    // 删除所有SQL验证相关方法
    // static _validateInput(sql, params) { ... }
    // static _validateIdentifiers(ast) { ... }
    // static _extractIdentifiers(ast) { ... }
    // static _validateIdentifier(identifier) { ... }
    // static _traverseAst(node, callback = null) { ... }
    // static _validateParams(params) { ... }
    // static _validateParam(value, index) { ... }
    // static _isRiskValue(value) { ... }

    /**
     * 关闭数据库连接池
     * @returns {Promise<void>}
     */
    static async closePool() {
        if (this.pool) {
            await this.pool.end();
            this.pool = null;
            this.initialized = false;
            logger.info('数据库连接池已关闭');
        }
    }
}